import Vue from 'vue';
import axios from 'axios';
import dataService from './apiService';

let baseUrl;
const DEVICE_IS_IOS = /iP(ad|hone|od)/.test(navigator.userAgent);


if (process.env.NODE_ENV === 'production') {
    baseUrl = 'https://mapi.bestpay.com.cn/mapi';
} else if (process.env.NODE_ENV === 'pre') {
    baseUrl = 'https://mapi-pre.bestpay.com.cn/mapi';
} else if (process.env.NODE_ENV === 'development') {
    baseUrl = 'https://mapi.test.bestpay.net/mapi';
}

const isInBestpay = (()=> {
    var ua = window.navigator.userAgent;
    return ua.toLowerCase().indexOf('bestpay') > -1 ? true : false;
})()

const getAppType =(()=>{
    if(isInBestpay){
        if (DEVICE_IS_IOS) {
            return '01'
        }else{
            return '00'
        }
    }else{
        return '45'
    }
})();

async function asyncBuildParams(params) {
    const newParams = params;
    newParams.sessionKey = await Vue.$util.getSessionKey();
    newParams.productNo = await Vue.$util.getProductNo();
    newParams.appType = getAppType;

    const timestamp = new Date().getTime();
    newParams.timestamp = timestamp.toString();
    // console.log('加密前请求参数：', JSON.stringify(newParams));
//  newParams = await Vue.prototype.$Encrypt.asnyBuildCAParams(JSON.stringify(newParams), newParams.productNo);
    return newParams;
}
function run(serviceName, params) {
    return new Promise(async resolve => {
        const service = dataService[serviceName];
        if (!service) {
            console.log('方法不存在');
            return;
        }
        const newParams =  await asyncBuildParams(params); // 加密前的参数
        // const newParams = params
        // const laterParams = await Vue.prototype.$Encrypt.asnyBuildCAParams(JSON.stringify(newParams), newParams.productNo); // 加密后的参数
        const method = service.method;
        let url = `${baseUrl}/${service.url}`;
        // console.log(`${serviceName}请求参数：${JSON.stringify(params)}`);
        if (service.isMock) {
            url = service.mockUrl;
            axios.get(url)
                .then((res) => {
                    resolve(res)
                })
                .catch((error) => {
                    resolve(error)
                });
        } else {
            const config = {
                method,
                url,
                headers: { 'content-type': 'application/json;charset=UTF-8' },
                data: newParams ,
                // data: method === 'post' || method === 'put' ? (conType ? JSON.stringify(params) : Qs.stringify(newParams)) : null,
                // params: method === 'get' || method === 'delete' ? Qs.stringify(newParams) : null,
            }
            // console.log(config)
            axios(config)
                .then((res) => {
                    // console.log(`${serviceName}获取数据: ${JSON.stringify(res.data)}`);
                    if (res.data.errorCode === '100003') {
                        //对错误做处理
                        return;
                    }
                    resolve(res)
                })
                .catch((err) => {
                    console.log(`err ${err}`);
                    resolve(err)
                });
        }
//  })
    })
}

export default {
    run,
    baseUrl
};
